import pickle
import base64
from django_redis import get_redis_connection

def merge_cart_cookie_to_redis(request, user, response):
    '''合并购物车数据 将cookie中的数据合并保存到redis中'''
    # 获取cookie中的购物车
    cookie_cart = request.COOKIES.get('cart')
    if cookie_cart:
        cookie_cart_dict = pickle.loads(base64.b64decode(cookie_cart.encode()))
    else:
        cookie_cart_dict = {}

    if not cookie_cart_dict:
        return response

    # 获取redis中的购物车数据
    redis_conn = get_redis_connection('cart')
    redis_cart = redis_conn.hgetall('cart_%s' % user.id)
    pl = redis_conn.pipeline()

    redis_cart_dict = {}
    for sku_id, count in redis_cart.items():
        redis_cart_dict[int(sku_id)] = int(count)

    # 记录redis勾选状态中应该增加的sku_id
    redis_cart_selected_add = []

    # 记录redis勾选状态中应该删除的sku_id
    redis_cart_selected_remove = []

    for sku_id, count_selected_dict in cookie_cart_dict.items():
        # 处理商品的数量
        # 构造redis中购物车数据的最终字典
        redis_cart_dict[sku_id] = count_selected_dict['count']

        # 处理勾选状态
        selected = count_selected_dict['selected']

        sku_id = str(sku_id).encode()

        if selected:
            redis_cart_selected_add.append(sku_id)
        else:
            redis_cart_selected_remove.append(sku_id)

    # 执行redis的命令 设置hash的字典数据和勾选的set数据
    if redis_cart_dict:
        pl.hmset('cart_%s' % user.id, redis_cart_dict)

    if redis_cart_selected_remove:
        pl.srem('cart_selected_%s' % user.id, *redis_cart_selected_remove)

    if redis_cart_selected_add:
        pl.sadd('cart_selected_%s' % user.id, *redis_cart_selected_add)

    pl.execute()

    # 删除cookie中的购物车数据
    response.delete_cookie('cart')
    return response